
<template>
  <div
    :class="['suspendBox', { move: !canDrag }]"
    :style="{top:top+'px',left:left+'px',cursor:'pointer'}"
    @mousedown="start"
    @mousemove="move"
    @mouseup="stop"
    @mouseenter="enter"
    @mouseleave="leave"
  >
    <a-icon type="snippets" :style="{color:' #333', fontSize: '18px',}" class="suspendBoxContent" />
    <a-modal v-model="showModal" title="任务列表" :width="1200" :footer="null">
      <a-icon type="sync" style="position: absolute;z-index: 1000;font-size: 15px;top: 20px;left: 95px;" :spin="loading" @click="getData" />
      <standard-table :columns="columns" :data-source="dataSource" row-key="id" :pagination="{showTotal:total => `共 ${count} 个任务`, total: count, pageSize: pagesize}" @change="onChange" :loading="loading">
        <div slot="status" slot-scope="{record}" >
          <span :style="record.status==1?'color:#fa541c':'color:#52c41a'">
            {{record.status==1?'进行中':'已完成'}}
          </span>
        </div>
        <div slot="create_time" slot-scope="{record}">
          {{moment(record.create_time*1000).format("YYYY-MM-DD HH:mm:ss")}}
        </div>
        <div slot="start_time" slot-scope="{record}">
          {{record.start_time == 0 ? '-' : moment(record.start_time*1000).format("YYYY-MM-DD HH:mm:ss")}}
        </div>
        <div slot="update_time" slot-scope="{record}">
          {{record.status == 2?moment(record.update_time*1000).format("YYYY-MM-DD HH:mm:ss"):'-'}}
        </div>
        <div slot="action" slot-scope="{record}">
          <a href="javascript:;" @click="getResult(record.result, record.bdaccounts)" v-if="record.result != '' && record.status == 2" style="color:rgb(255, 120, 117)">
            <a-icon type="close-circle" /> 错误信息
          </a>
          <a href="javascript:;" v-if="record.result == '' && record.status == 1" >
            <div v-if="record.start_time == 0" style="color:#f5454e;display: flex;align-items: center;">
              <div style="margin-right: 10px;" @click="getSuccess(record.bdaccounts)">
                <a-icon type="info-circle" /> 等待中
              </div>
              <a-popconfirm title="确认关停计划？" @confirm="stopQueueJob(record.id)" >
                <a-icon type="close-circle" /> 关停
              </a-popconfirm>
            </div>
            <div v-else style="color:rgb(250, 173, 20)" @click="getSuccess(record.bdaccounts)">
              <a-icon type="info-circle" /> 进行中
            </div>
          </a>
          <a href="javascript:;" v-if="record.result == '' && record.status == 2" style="color:rgb(82, 196, 26)" @click="getSuccess(record.bdaccounts)">
            <a-icon type="check-circle" /> 操作成功
          </a>
        </div>
      </standard-table>
    </a-modal>
    <a-modal v-model="showMsgBox" title="任务结果" :footer="null">
      <div class="msgBoxContent" v-if="msgList.length > 0">
        <span v-for="(item,index) in bdaccounts" :key="'bd' + index">
          <a href="javascript:;" @click="goETrade(item.id,item.account)" >{{ item.account }}</a>
          <span v-if="index < bdaccounts.length - 1">、</span>
        </span>
        <p v-for="(item,index) in msgList" :key="index">{{ item }}</p>
      </div>
      <a-empty v-else />
    </a-modal>
    <a-modal v-model="showBdaccountBox" title="账户信息" :footer="null">
      <div class="msgBoxContent" v-if="bdaccounts.length > 0">
        <span v-for="(item,index) in bdaccounts" :key="index">
          <a href="javascript:;" @click="goETrade(item.id,item.account)" >{{ item.account }}</a>
          <span v-if="index < bdaccounts.length - 1">、</span>
        </span>
      </div>
      <a-empty v-else />
    </a-modal>
  </div>
</template>

<script>
import { getTasksByUser } from '@/api/shuju/shuju'
import { stopQueueJob } from '@/api/dianshang/dianshang'
import StandardTable from '@/components/table/StandardTable'
import moment from 'moment';

export default {
  props:{
    ableMove: {type: Boolean, default: true},  //是否可移动
    ableHide: {type: Boolean, default: true},  //是否靠边隐藏
    hoverShow: {type: Boolean, default: true},  //图标隐藏时 鼠标悬浮即展示，否则点击展示
    distance: {type: Number, default: 5},  //距离边界多少px就隐藏
    defaultX: {type: Number, default: 1},  //初始横坐标百分比
    defaultY: {type: Number, default: 0.8}  //初始纵坐标百分比
  },
  data() {
    return {
      moment,
      canDrag: false,
      isClick: false,
      x0: 0,
      y0: 0,
      top: null,
      left: null,

      initTimeOut:null,
      showModal:false,
      page:1,
      pagesize:10,
      dataSource:[],
      count:0,
      columns:[
        {
          title: 'ID',
          dataIndex: 'id',
        },
        {
          title: '任务类型',
          dataIndex: 'task_type',
        },
        {
          title: '任务内容',
          dataIndex: 'task_content',
        },
        // {
        //   title: '任务状态',
        //   dataIndex: 'status',
        //   scopedSlots: { customRender: 'status' },
        //   // sorter: (a, b) => a.status - b.status,
        // },
        {
          title: '创建时间',
          dataIndex: 'create_time',
          scopedSlots: { customRender: 'create_time' },
          // sorter: (a, b) => a.create_time - b.create_time,
        },
        {
          title: '开始时间',
          dataIndex: 'start_time',
          scopedSlots: { customRender: 'start_time' },
        },
        {
          title: '完成时间',
          dataIndex: 'update_time',
          scopedSlots: { customRender: 'update_time' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          width:160,
          scopedSlots: { customRender: 'action' },
        },
      ],
      loading:false,
      msgList:[],
      bdaccounts:[],
      showMsgBox:false,
      showBdaccountBox:false,

      reloadSpin:false,
    };
  },
  created(){
    // console.log('created')
  },
  mounted() {
    this.init()
    window.addEventListener('resize', () => {
      this.init()
    })
  },
  methods: {
    init(){
      let img = document.querySelector(".suspendBox");
      let box = document.documentElement;
      this.left = (box.offsetWidth - img.offsetWidth) * this.defaultX;
      this.top = (box.offsetHeight - img.offsetHeight) * this.defaultY;
      clearTimeout(this.initTimeOut)
      this.initTimeOut = setTimeout(()=>{
        this.hide()
      }, 1000)
    },
    getData(){
      let params = {
        page: this.page,
        pagesize: this.pagesize,
      }
      this.loading = true
      getTasksByUser(params).then((res) => {
        this.loading = false
        if(res.errcode == 0){
          this.dataSource = res.data.taskLists
          this.count = res.data.taskCount
        }
      }).catch(() => {
        this.loading = false
      });
    },
    stopQueueJob(id) {
      const hide = this.$message.loading('关停中')
      stopQueueJob({id}).then((res) => {
        if (res.errcode == 0) {
          hide()
          this.getData()
        }
      }).catch(() => {
        hide()
      });
    },
    onChange(e){
      if(e.current != this.page){
        this.page = e.current
        this.getData()
      }
    },
    getSuccess(bdaccounts){
      // console.log(bdaccounts)
      this.bdaccounts = bdaccounts
      this.showBdaccountBox = true
    },
    getResult(res, bdaccounts){
      this.msgList = this.goResult(res)
      // console.log(this.msgList)
      this.bdaccounts = bdaccounts
      this.showMsgBox = true
    },
    goETrade(id,name){
      this.$store.commit('dianpu/setId',{id,name})  //保存id
      // this.$router.resolve('/etrade')
      let routeUrl = this.$router.resolve({
        path: "/etrade",
      });
      window.open(routeUrl.href, '_blank');
    },
    goResult(res){
      // 递归获取结果中的message
      let result = []
      if(!res){return []}
      if(typeof res === 'object'){
        for(let [key,val] of Object.entries(res)){
          if(key == 'message'){
            result.push(val)
            break;
          }else if(key == 'desc' && val != 'failure'){
            result.push(val)
          }else{
            if(typeof val === 'object'){
              result = result.concat(this.goResult(val))
            }
          }
        }
      }
      return result
    },
    start(e) {
      e.preventDefault();   //阻止默认的拖拽
      if (e.button == 0) {
        this.canDrag = this.ableMove;
        this.isClick = true;
        this.x0 = e.clientX;
        this.y0 = e.clientY;
      }
    },
    move(e) {
      // console.log("move");
      if (this.canDrag == true) {
        this.isClick = false;
        let x = e.clientX - this.x0;
        let y = e.clientY - this.y0;
        let img = document.querySelector(".suspendBox");
        let box = document.documentElement;
        if (
          img.offsetLeft + x < 0 ||
          img.offsetTop + y < 0 ||
          img.offsetLeft + x > box.offsetWidth - img.offsetWidth ||
          img.offsetTop + y > box.offsetHeight - img.offsetHeight
        ) {
          return false;
        }
        this.left = img.offsetLeft + x;
        this.top = img.offsetTop + y;
        this.x0 = e.clientX;
        this.y0 = e.clientY;
      }
    },
    stop() {
      this.canDrag = false;
      // console.log("stop");
      this.show();
    },
    enter() {
      // console.log("enter");
      if (this.hoverShow) {
        this.show();
      }
    },
    leave() {
      // console.log("leave");
      this.canDrag = false;
      this.hide();
    },
    show() {
      let img = document.querySelector(".suspendBox");
      let box = document.documentElement;
      // console.log(img.offsetLeft, this.isClick)
      if (img.offsetLeft < 0) {
        this.left = 0;
      } else if (img.offsetLeft > box.offsetWidth - img.offsetWidth) {
        this.left = box.offsetWidth - img.offsetWidth
      } else if(this.isClick){
        this.clickEvent()
      }
    },
    hide() {
      if (this.ableHide) {
        let img = document.querySelector(".suspendBox");
        let box = document.documentElement;
        // console.log("hide", img.offsetLeft , box.offsetWidth - img.offsetWidth - this.distance);
        if (!this.canDrag && img.offsetLeft < this.distance) {
          this.left = -img.offsetWidth * 2 / 3;
        } else if (!this.canDrag && img.offsetLeft > box.offsetWidth - img.offsetWidth - this.distance) {
          this.left = box.offsetWidth - img.offsetWidth / 3
        }
      }
    },
    clickEvent() {      //悬浮窗的点击事件
      // console.log("悬浮窗的点击事件");
      this.showModal = true
      this.isClick = false
    },
  },
  watch:{
    showModal(val){
      if(val){
        this.getData()
      }
    }
  },
  components:{StandardTable}
};
</script>
<style scoped>
.msgBoxContent{
  height: 300px;
  overflow-y: auto;
  overflow-x: hidden;
}
.outBox {
  width: 100%;
  height: 100%;
  position: absolute;
  overflow: hidden;
  z-index:100;
  pointer-events: none;
}
.suspendBox {
  position: fixed;
  pointer-events: auto;
  z-index:100;
  border-radius: 50%;
  background-color: #fff;
  box-shadow: 0px 0px 10px #a7a7a7;
  width: 45px;
  height: 45px;
}
.suspendBoxContent{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.move {
  transition: 0.3s linear;
  -moz-transition: 0.3s linear; /* Firefox 4 */
  -webkit-transition: 0.3s linear; /* Safari 和 Chrome */
  -o-transition: 0.3s linear; /* Opera */
}
</style>
